<!doctype html>



  


<html class="theme-next muse use-motion">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  
  
  <link href="/vendors/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/vendors/font-awesome/css/font-awesome.min.css?v=4.4.0" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.0.1" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="jvm," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.0.1" />






<meta name="description" content="标签（空格分隔）： jvm

关于JVM的永久代问题，自jdk1.7起就提出要去除永久代，不仅有大家都知道的回收困难，当然还有一些其他的原因，致使永久代随着java版本的更替渐行渐远，慢慢背离他原本的设计初衷。
在这里就讲讲关于永久代的那点事，以及jdk1.6以及之后的版本因为永久代的缘故而产生的差异">
<meta property="og:type" content="article">
<meta property="og:title" content="JVM内存模型">
<meta property="og:url" content="http://yoursite.com/2016/08/28/jvm-memory/index.html">
<meta property="og:site_name" content="个人博客">
<meta property="og:description" content="标签（空格分隔）： jvm

关于JVM的永久代问题，自jdk1.7起就提出要去除永久代，不仅有大家都知道的回收困难，当然还有一些其他的原因，致使永久代随着java版本的更替渐行渐远，慢慢背离他原本的设计初衷。
在这里就讲讲关于永久代的那点事，以及jdk1.6以及之后的版本因为永久代的缘故而产生的差异">
<meta property="og:updated_time" content="2017-01-19T07:14:13.340Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="JVM内存模型">
<meta name="twitter:description" content="标签（空格分隔）： jvm

关于JVM的永久代问题，自jdk1.7起就提出要去除永久代，不仅有大家都知道的回收困难，当然还有一些其他的原因，致使永久代随着java版本的更替渐行渐远，慢慢背离他原本的设计初衷。
在这里就讲讲关于永久代的那点事，以及jdk1.6以及之后的版本因为永久代的缘故而产生的差异">



<script type="text/javascript" id="hexo.configuration">
  var NexT = window.NexT || {};
  var CONFIG = {
    scheme: 'Muse',
    sidebar: {"position":"left","display":"post"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: 0,
      author: '博主'
    }
  };
</script>




  <link rel="canonical" href="http://yoursite.com/2016/08/28/jvm-memory/"/>

  <title> JVM内存模型 | 个人博客 </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  










  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">个人博客</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle">随便写点什么</p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      

      
    </ul>
  

  
</nav>

 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                JVM内存模型
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">发表于</span>
            <time itemprop="dateCreated" datetime="2016-08-28T15:51:00+08:00" content="2016-08-28">
              2016-08-28
            </time>
          </span>

          
            <span class="post-category" >
              &nbsp; | &nbsp;
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/jvm/" itemprop="url" rel="index">
                    <span itemprop="name">jvm</span>
                  </a>
                </span>

                
                

              
            </span>
          

          
            
              <span class="post-comments-count">
                &nbsp; | &nbsp;
                <a href="/2016/08/28/jvm-memory/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count ds-thread-count" data-thread-key="2016/08/28/jvm-memory/" itemprop="commentsCount"></span>
                </a>
              </span>
            
          

          

          
          

          
        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>标签（空格分隔）： jvm</p>
<hr>
<p>关于JVM的永久代问题，自jdk1.7起就提出要去除永久代，不仅有大家都知道的回收困难，当然还有一些其他的原因，致使永久代随着java版本的更替渐行渐远，慢慢背离他原本的设计初衷。</p>
<p>在这里就讲讲关于永久代的那点事，以及jdk1.6以及之后的版本因为永久代的缘故而产生的差异</p>
<hr>
<a id="more"></a>
<p>好，那废话不多说，直接进入主题，先上代码。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">String str1 = <span class="keyword">new</span> StringBuilder(<span class="string">"计算机"</span>).append(<span class="string">"软件"</span>).toString();</div><div class="line">String str2 = <span class="keyword">new</span> StringBuilder(<span class="string">"ja"</span>).append(<span class="string">"va"</span>).toString();</div><div class="line"></div><div class="line">System.out.println(str1.intern() == str1);<span class="comment">//jdk1.7为true，jdk1.6为false</span></div><div class="line">System.out.println(str2.intern() == str2);<span class="comment">//jdk1.7 为false，jdk1.6为false</span></div></pre></td></tr></table></figure></p>
<p>那为何会出现这样的结果？<br>这是跟jdk1.6与1.7这两个版本对于永久代的不同处理导致的。<br>先看jdk1.6，调用intern时，若是在永久代中未出现过该字符串，则会把该字符换实例复制到永久代中，注意是<strong>实例</strong>，而用StringBuilder new出来的对象是保存在堆上的，两者必然不是同一个引用，比较后返回的自然就是false。</p>
<p>而jdk1.7中，改变了1.6复制实例的做法，而是保存其引用，也就是说，一个字符串调用intern时，若是该字符串是第一次在永久代中出现，就在永久代中保存该字符串的引用。如此之下，str1比较的其实就是同一个引用，自然返回的是true。而为什么“java”却返回的是false呢，是因为str2在调用intern时发现“java”不是首次在永久代中出现，也就是说之前就已经存在与永久代中，那么自然就不会保存他的引用。所以比较时两者其实是不同的引用，所以返回false。</p>
<p>当然你可能会问，“java”的引用是什么时候被置入永久代的。这个我倒没有研究过，我猜应该是JVM在启动的时候被放进去的，就像“system”一样，他也是一早就出现在永久代中的。</p>
<p>说到这里的 “==” ，想到之前看过的一个比较有趣的问题，这里也拿出来跟大家分享下（该问题与永久代无关）</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line">Integer i1 = <span class="number">1</span>;</div><div class="line">Integer i2 = <span class="number">1</span>;</div><div class="line">Integer i3 = <span class="number">129</span>;</div><div class="line">Integer i4 = <span class="number">129</span>;</div><div class="line">System.out.println(i1 == i2); <span class="comment">// true</span></div><div class="line">System.out.println(i3 == i4); <span class="comment">// false</span></div></pre></td></tr></table></figure>
<p>哈，有的人可能会说了，诶，这个基本对象类型用==比较时不是值比较吗，不是有自动拆箱的过程吗，为什么是false啊。</p>
<p>关于这个问题的话，我们分两点说明<br>1.基本对象类型的比较<br>确实，基本对象类型用==比较是值比较，但是Integer是int的包装类型，比如我们用<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">int</span> a = <span class="number">129</span>;</div><div class="line">Integer b = <span class="number">129</span>;</div><div class="line">Sysout.out.println(a == b);</div></pre></td></tr></table></figure></p>
<p>确实会得到结果为true。<br>但是如果比较的两者都是包装类型，那么就从单纯的基本数据类型的值比较升级成了对象的比较。</p>
<p>2.对象的比较<br>既然知道了<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">Integer i3 = <span class="number">129</span>;</div><div class="line">Integer i4 = <span class="number">129</span>;</div></pre></td></tr></table></figure></p>
<p>是对象比较，那为何i1 == i2 为true而这个为false？<br>这里需要稍微看一下源码。<br>首先：在对Integer引用直接赋值时，默认调用的是Integer.valueOf(int i);<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> Integer <span class="title">valueOf</span><span class="params">(<span class="keyword">int</span> i)</span> </span>&#123; </div><div class="line"> <span class="keyword">if</span> (i &gt;= IntegerCache.low &amp;&amp; i &lt;= IntegerCache.high)</div><div class="line"> <span class="keyword">return</span> IntegerCache.cache[i + (-IntegerCache.low)]; </div><div class="line"> <span class="keyword">return</span> <span class="keyword">new</span> Integer(i); </div><div class="line"> &#125;</div></pre></td></tr></table></figure></p>
<p>看到这里是不是就有点门路了，有个叫IntegerCache.cache的鬼东西。<br>而IntegerCache.cache是一个Integer[]，其中IntegerCache是Integer的一个静态内部类。<br>它有这么几个字段<br><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">int</span> low = -<span class="number">128</span>; </div><div class="line"><span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">int</span> high;    <span class="comment">//通常有JVM启动参数决定，默认127</span></div><div class="line"><span class="keyword">static</span> <span class="keyword">final</span> Integer cache[];</div></pre></td></tr></table></figure></p>
<p>好，那看到这里我觉得其实已经差不多了，也就是说JVM启动后给Integer初始化了一个内部数组，方便我们直接赋值。<br>比如Integer i = 1，这样的赋值方式，直接从cache数组里与之对应的Integer对象，然后i持有其引用。<br>在进一步说，只要是cache数组内有的，我们赋值方式是用Integer i = 1这样的简单赋值的，只要值相同，那么他们指向的都是一个实例。<br>这就说明了为何上面程序的i1 == i2 为true。<br>相应的，i3 == i4 为false是因为cache中没有对应的Integer对象，那么赋值的时候其实是new了2个对象然后交给i3跟i4， 那么i3与i4拿到的其实是两个对象，自然 == 比较后就是false。<br>这里的关键是存在一个内部预初始化的数组，所以会出现这样比较奇特的结果。</p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/jvm/" rel="tag">#jvm</a>
          
        </div>
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2016/08/28/java-hashmap/" rel="next" title="Java之HashMap在非线程安全时的行为">
                <i class="fa fa-chevron-left"></i> Java之HashMap在非线程安全时的行为
              </a>
            
          </div>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2016/08/28/spring-boot-1/" rel="prev" title="spring boot实战（1）">
                spring boot实战（1） <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
      <div class="ds-thread" data-thread-key="2016/08/28/jvm-memory/"
           data-title="JVM内存模型" data-url="http://yoursite.com/2016/08/28/jvm-memory/">
      </div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel ">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/uploads/touxiang.jpg"
               alt="钱伟峰" />
          <p class="site-author-name" itemprop="name">钱伟峰</p>
          <p class="site-description motion-element" itemprop="description">每天进步一点点</p>
        </div>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">21</span>
              <span class="site-state-item-name">日志</span>
            </a>
          </div>

          
            <div class="site-state-item site-state-categories">
              <a href="/categories">
                <span class="site-state-item-count">7</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags">
                <span class="site-state-item-count">11</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        

      </section>

      
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">
            
              
            
            
              <p class="post-toc-empty">此文章未包含目录</p>
            
          </div>
        </section>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">钱伟峰</span>
</div>

<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Muse
  </a>
</div>

        

        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  



  
  <script type="text/javascript" src="/vendors/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/vendors/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/vendors/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.0.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.0.1"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.0.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.0.1"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.0.1"></script>



  

  
    
  

  <script type="text/javascript">
    var duoshuoQuery = {short_name:"qianweifeng"};
    (function() {
      var ds = document.createElement('script');
      ds.type = 'text/javascript';ds.async = true;
      ds.id = 'duoshuo-script';
      ds.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//static.duoshuo.com/embed.js';
      ds.charset = 'UTF-8';
      (document.getElementsByTagName('head')[0]
      || document.getElementsByTagName('body')[0]).appendChild(ds);
    })();
  </script>

  
    
    <script src="/vendors/ua-parser-js/dist/ua-parser.min.js?v=0.7.9"></script>
    <script src="/js/src/hook-duoshuo.js"></script>
  






  
  

  

  

  

</body>
</html>
